package com.nulldev.util.networking.dns.client.transport;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.nio.ByteBuffer;

import com.nulldev.util.io.IOUtils;
import com.nulldev.util.networking.dns.client.Message;

public class UDPTransport extends DNSTransport {

	public static final int MAX_PACKET_SIZE = 512;

	public static final int PORT = 53;

	private final InetAddress server;
	private final int port;

	public UDPTransport(InetAddress server) {
		this(server, PORT);
	}

	public UDPTransport(InetAddress server, int port) {
		this.server = server;
		this.port = port;
	}

	@Override
	public Message sendQuery(Message requestMessage) throws IOException {
		byte[] messageBytes = serializeMessage(requestMessage, MAX_PACKET_SIZE);

		DatagramPacket requestPacket = new DatagramPacket(messageBytes, messageBytes.length, server, port);

		try {
			DatagramSocket s = new DatagramSocket();
			s.send(requestPacket);

			byte[] buf = new byte[8196];
			DatagramPacket response = new DatagramPacket(buf, buf.length);
			s.receive(response);

			byte[] responseBytes = new byte[response.getLength()];
			System.arraycopy(response.getData(), response.getOffset(), responseBytes, 0, response.getLength());

			ByteBuffer byteBuffer = ByteBuffer.wrap(responseBytes);
			Message responseMessage = new Message().fromBytes(byteBuffer);

			IOUtils.closeQuietly(s);
			return responseMessage;
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException();
		}
	}

}
